<template>
    <div class="top_bar">
        <div class="logo"><img src="https://bu.dusays.com/2024/09/28/66f7782a0e175.png" alt=""></div>
        <div class="farm_card">
            <div class="card_left">
                <span>{{ room_info.roomName }}</span>
                <div class="card_tags" style="display: flex; gap: 1vh;">
                    <el-tag style="margin: 0;" effect="dark">实力商家</el-tag>
                    <el-tag style="margin: 0;" effect="dark">实力商家</el-tag>
                </div>
            </div>
            <div class="card_right">
                <div class="right_1">
                    <div style="color: #949494;" class="rating">商铺评分</div>
                    <span>{{ room_info.roomRating }}</span>
                </div>
                <div class="right_2">
                    <div style="color: #949494;" class="items">商品数量</div>
                    <span>{{ room_info.roomItems }}+</span>
                </div>
                <div class="right_3">
                    <div style="color: #949494;" class="total">成交总金额</div>
                    <span>{{ room_info.roomTotal }}万</span>
                </div>


            </div>
        </div>
        <div class="search">
            <el-input v-model="search_input" placeholder="热门商品" :prefix-icon="Search" />
            <div class="search_btn">
                <v-btn style="color: white;" class="search_btn_v" :ripple="false" height="4vh" min-width="10vh">
                    搜索
                </v-btn>
            </div>
        </div>
    </div>
    <div class="select_bar">
        <v-btn href="/user" variant="text">首页</v-btn>
        <v-btn @click="goRoom()" variant="text">店铺</v-btn>
        <v-btn @click="router.push(`/qr/${traceUid}`)" variant="text">溯源信息</v-btn>
        <el-popover trigger="hover" placement="bottom" :width="160">
            <el-image :src="qrImg"></el-image>
            <template #reference>
                <v-btn  variant="text">溯源码</v-btn>
            </template>
        </el-popover>
    </div>
    <div class="body">
        <div class="one_box">
            <div class="one_right">
                <div class="right_body">
                    <div class="one_title">
                        <h1>{{ items.itemName }}</h1>
                    </div>
                    <div class="one_desc">
                        <span>{{ items.itemDesc }}</span>
                    </div>
                    <div class="one_rate">
                        <el-rate v-model="items.itemRate" disabled show-score text-color="#ff9900"
                            :score-template="`${items.itemRate} 分`" />
                    </div>
                    <div class="one_price">
                        <h3 style="display: flex; gap: 1vh;font-size: 3.5vh;">
                            <h3 style="color: #FF5C19;margin-top: -0.2vh;">￥{{
                                items.itemPrice }}元</h3>
                        </h3>
                    </div>
                    <div class="one_address">
                        <h3 style="font-size: 2vh;color:#949494;font-weight:normal">
                            配送:&nbsp;&nbsp;&nbsp;<span style="color: black;">{{ items.itemAddress }}
                                &nbsp;&nbsp;至&nbsp;&nbsp;
                                {{ city }}&nbsp;&nbsp;</span>
                            <span @click="toggleAddresses" class="arrow-icon">
                                <el-icon :class="{ 'rotate-up': !rotate, 'rotate-down': rotate }">
                                    <ArrowDownBold />
                                </el-icon>
                            </span>
                        </h3>
                        <div v-if="showAddresses" class="address-list">
                            <ul>
                                <span style="font-weight: bold;">选择配送地址</span>
                                <div v-for="item in otherAddresses" :key="item.addressId" class="Address_card"
                                    @click="selectAdd(item.city)">
                                    <div class="Address_up" style="margin-left: 1vh;">
                                        <span style="font-weight: bold;font-size: 1.2vh;">{{ item.recipientName
                                        }}&nbsp;&nbsp;&nbsp;</span>
                                        <span style="font-size: 1.2vh;color: gray;">{{ item.phoneNumber }}</span>
                                    </div>
                                    <div class="Address_down" style="margin-left: 1vh;">
                                        <span style="font-size: 1.2vh;color: gray;">{{ item.province }}&nbsp;{{ item.city
                                        }}&nbsp;{{ item.district }}&nbsp;{{ item.detailAddress }}</span>
                                    </div>
                                </div>
                            </ul>
                        </div>
                    </div>
                    <div class="one_sure">
                        <h3 style="font-size: 2vh;color:#949494;font-weight:normal">保障:&nbsp;&nbsp;&nbsp;<span
                                style="color: black;">产地直发 坏单包退 生鲜极速退</span></h3>
                    </div>
                    <div class="one_size">
                        <h3 style="font-size: 2vh;color:#949494;font-weight:normal">商品规格:&nbsp;&nbsp;&nbsp;<span
                                style="color: black;">{{ items.itemPrice }}{{ items.itemUnit }}</span></h3>
                    </div>
                    <div class="one_buyNum">
                        <h3 style="font-size: 2vh;color:#949494;font-weight:normal;margin-top: 0.5vh;">数量:&nbsp;&nbsp;&nbsp;
                        </h3>
                        <el-input-number style="height: 4.5vh;width: 20vh;" v-model="buyNum" :min="1" :max="10"
                            @change="handleChange"></el-input-number>
                        <h3 v-if="items.itemStock > 200" class="buyTotal"
                            style="margin-top: 0.5vh;margin-left: 2vh;color: #949494;font-weight: normal;">有货</h3>
                        <h4 v-else class="buyTotal"
                            style="margin-left: 1vh;margin-top: 1vh;color: #949494;font-weight: normal;">
                            {{ items.itemStock }}件</h4>
                        <div style="display: flex;" class="one_btn">
                            <el-button @click="buyNow(items.itemID)" style="margin-left: 2vh;width: 8vh;height: 4.5vh;"
                                type="danger">立即下单</el-button>
                            <el-button @click="joinCart" style="width: 10vh;height: 4.5vh;" type="warning">加入购物车</el-button>
                            <el-button v-if="ifFav == false" @click="joinFav" style="height: 4.5vh;" type="default"
                                icon="Star">收藏</el-button>
                            <el-button v-else style="height: 4.5vh;" type="success">已收藏</el-button>
                            <el-button @click="openChat" style="height: 4.5vh;width: 8vh;" type="primary">联系客服</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="one_left">
                <img :src="`https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/商品列表/List/${items.itemImg}.jpg`" alt=""
                    class="img_box" />
                <button v-if="items.free" @click="GetFreeItem" class="free_button">
                    天天领水果
                </button>
            </div>
        </div>
        <div class="two_box">
            <div v-for="item in url_list" :key="item" class="image-container">
                <el-image
                    style="height: 100%; width: 60%;border-radius: 10px;margin-top: 2vh;box-shadow: #949494 0vh 0vh 1vh 0.2vh;"
                    :src="`https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/商品图片表/${item.imagePath}.jpg`"
                    alt=""></el-image>
            </div>
        </div>
        <div class="three_box"></div>
    </div>
    <div>
        <el-dialog v-model="visible" title="客服聊天" width="30%">
            <div class="chat-window">
                <div class="chat-messages" ref="messages">
                    <div v-for="message_info in messages_list" class="message">
                        <div
                            :class="{ 'message-sender': message_info.from === username, 'message-receiver': message_info.from !== username }">

                            <!-- 店铺头像 -->
                            <img v-if="message_info.from !== username" :src="shopAvatar" alt="Shop Avatar"
                                class="avatar avatar-receiver">
                            <!-- 消息内容 -->
                            <div class="message-content">
                                <strong>
                                    <span v-if="message_info.from === username">{{ user.name }}</span>
                                    <span v-else>{{ room_info.roomName }}</span>:
                                </strong>
                                {{ message_info.text }}
                                <br>
                                <span style="font-size: 0.8em; color: gray;">{{ formatTimestamp(message_info.timestamp)
                                }}</span>
                            </div>
                            <!-- 用户头像 -->
                            <img v-if="message_info.from === username" :src="userAvatar" alt="User Avatar"
                                class="avatar avatar-sender">
                        </div>
                    </div>
                </div>
                <el-input v-model="inputMessage" placeholder="输入消息" @keyup.enter="sendMessage">
                    <template #append>
                        <el-button @click="sendMessage">发送</el-button>
                    </template>
                </el-input>
            </div>
        </el-dialog>
    </div>
    <Footer></Footer>
</template>
<script setup>
import Footer from '@/component/Footer.vue'
import { Calendar, Search } from '@element-plus/icons-vue';
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import router from '../../router/index.js'
import { ref, onMounted, onUnmounted } from 'vue';
import request from '../../utils/request';
import { reactive } from "vue";
import { ElNotification } from 'element-plus'


const visible = ref(false);
const QRvisible = ref(false);
const inputMessage = ref('');
const messages = ref([]);
const username = ref(''); // 当前用户的username
const toUsername = ref(''); // 店铺的username
const userAvatar = ref('');
const shopAvatar = ref('');
const socket = ref(null);
const messages_list = ref({});
const traceUid = ref()
const qrImg = ref()

const buyNum = ref(1)

const items = ref([])
const url_list = ref([])
const room_info = ref([])
var roomId = ref(0)
const city = ref("选择发货地址");

const user = ref({});

const openChat = () => {
    visible.value = true;
    connectWebSocket();
}

const connectWebSocket = () => {
    socket.value = new WebSocket(`ws://localhost:9090/imserver/${username.value}`);

    socket.value.onmessage = (event) => {
        const message = JSON.parse(event.data);
        // messages_list.value.push(message);
        scrollToBottom(); // 滚动到消息列表底部
    };

    socket.value.onopen = () => {
        console.log('WebSocket connected');
        // 请求历史消息
        requestHistoryMessages();
    };

    socket.value.onclose = () => {
        console.log('WebSocket disconnected');
    };
};

const loading = ref(true);

const formatTimestamp = (timestamp) => {
    const date = new Date(timestamp);
    return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
};

const requestHistoryMessages = async () => {
    try {
        const response = await request.get('/api/message/history', {
            params: {
                sender: username.value,
                receiver: toUsername.value,
            }
        });
        if (response && Array.isArray(response)) {
            messages.value = response.map(msg => ({
                from: msg.sender,
                to: msg.receiver,
                text: msg.content,
                timestamp: new Date(msg.timestamp), // 确保时间戳是 Date 对象
                messageType: msg.messageType
            }));
            scrollToBottom();
            messages_list.value = messages.value;
            console.log("历史消息:", messages_list.value);
        } else {
            console.error("历史消息数据格式错误:", response);
        }
    } catch (error) {
        console.error('请求历史消息失败:', error);
    } finally {
        loading.value = false;
    }
};

const scrollToBottom = () => {
    const messagesContainer = document.querySelector('.chat-messages');
    if (messagesContainer) {
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
};

const sendMessage = () => {
    if (inputMessage.value.trim() === '') return;

    const message = {
        from: username.value,
        to: toUsername.value,
        text: inputMessage.value,
        timestamp: new Date(),
        messageType: 'text'
    };

    socket.value.send(JSON.stringify(message)); // 发送消息到WebSocket服务器
    messages_list.value.push(message); // 将发送的消息添加到消息列表
    inputMessage.value = ''; // 清空输入框
    scrollToBottom(); // 滚动到消息列表底部
};

const selectAdd = (itemCity) => {
    city.value = itemCity;
    rotate.value = !rotate.value;
    showAddresses.value = !showAddresses.value;
}

const uid = sessionStorage.getItem('uid');
const uidObj = JSON.parse(uid);


const joinCart = () => {
    const cart = ref({});
    cart.value.itemId = items.value.itemID;
    cart.value.quantity = buyNum.value;
    cart.value.uid = uidObj;
    console.log(cart.value);
    request.post("api/user/JoinCart", cart.value)
        .then(res => {
            console.log(res);
            ElNotification({
                title: '成功',
                message: '加入购物车成功',
                type: 'success',
            })
        })
        .catch(error => {
            console.error("加入购物车失败:", error);
            ElNotification({
                title: '失败',
                message: '加入购物车失败',
                type: 'error',
            })
        });
};

const goRoom = () => {
    window.open(`/roomdesc/${roomId}`, '_blank');
}

const joinFav = () => {
    const fav = ref({});
    fav.value.itemId = items.value.itemID;
    fav.value.id = user.id;
    request.post("/user/JoinFav", fav.value)
        .then(res => {
            console.log(res);
            ElNotification({
                title: '成功',
                message: '加入收藏成功',
                type: 'success',
            })
            window.location.reload();
        })
        .catch(error => {
            console.error("加入收藏失败:", error);
            ElNotification({
                title: '失败',
                message: '加入收藏失败',
                type: 'error',
            })
        })
}

const buyNow = (itemId) => {

    router.push(`/orderSubmit/${itemId}&${buyNum.value}`).then(() => {
        window.scrollTo(0, 0);
    })
}

const UserAddressUID = ref(0);


const showAddresses = ref(false);
const otherAddresses = ref([]);

const rotate = ref(false);


function toggleAddresses() {
    rotate.value = !rotate.value;
    showAddresses.value = !showAddresses.value;
}


const handleChange = (value) => {
    console.log(value);
}

const ifFav = ref(false);

const userInfo = () => {
    request.get('/api/user/GetUserInfo', {
        params: {
            uid: uidObj
        }
    }).then(res => {
        console.log("我是用户信息")
        console.log(res)
        username.value = res.data.username;
        user.value = res.data;
        userAvatar.value = res.data.avatar;
    })
}

const GetFreeItem = async () => {
    const isFarm = ref();

    await request.get("/api/ziziFarm/isFarm", {
        params: {
            uid: uidObj
        }
    }).then(res => {
        console.log("我是是否是农场", res.data);
        isFarm.value = res.data;
    })

    if (isFarm.value == "YesFarm") {
        ElNotification({
            title: '失败',
            message: '您有尚未完成的天天领取订单',
            type: 'error',
        })
    } else {
        request.post("/api/ziziFarm/goFarm", null, {
            params: {
                uid: uidObj,
                itemId: items.value.itemID
            }
        }).then(res => {
            console.log("我是领取结果", res);
        }
        )
    }
}

onMounted(async () => {
    const route = useRoute(); // 使用 useRoute 钩子获取当前路由对象
    const itemId = route.params.itemId; // 从路由对象中提取 id 参数
    userInfo();

    try {
        const itemRes = await request.get(`/api/item/selectItemById/${itemId}`).then(res => {
            items.value = res.data;
            roomId = res.data.itemOwner;
        }).catch(error => {
            console.error('请求失败:', error);
        });

        const urlRes = await request.get(`/api/item/selectItemUrlById/${itemId}`).then(res => {
            url_list.value = res.data;
            console.log(url_list.value);
        }).catch(error => {
            console.error('请求失败:', error);
        });

        const roomRes = await request.get(`/farmer/selectRoomById/${roomId}`).then(res => {
            room_info.value = res.data;
            toUsername.value = room_info.value.roomOwner;
        }).catch(error => {
            console.error('请求失败:', error);
            ElMessage.error("数据加载失败");
        });

        const farmerRes = await request.get("/farmer/selectFarmerByUsername", {
            params: {
                username: toUsername.value
            }
        }).then(res => {
            shopAvatar.value = res.data.avatar;
        })

        const data = reactive({
            user: JSON.parse(localStorage.getItem('system-user') || '{}')
        });

        UserAddressUID.value = user.value.uid;
        console.log("我是用户第" + UserAddressUID.value + "号");

        const addressRes = await request.get(`/api/user/selectUserAddressAll/${UserAddressUID.value}`).then(res => {
            otherAddresses.value = res.data;
            console.log(otherAddresses.value);
        }).catch(error => {
            console.error('请求失败:', error);
        });

        const favRes = await request.get(`/api/user/selectUserFavById/${UserAddressUID.value}?itemId=${itemId}`).then(res => {
            console.log(res.data);
            if (res.data == "已收藏") {
                ifFav.value = true;
            } else if (res.data == "未收藏") {
                ifFav.value = false;
            }
        });

        const traceRes = await request.get("/api/qr/GetTraceUid", {
            params: {
                itemId: itemId
            }
        }).then(res => {
            traceUid.value = res.data.traceUid;
            qrImg.value = res.data.qrImg;
            console.log(qrImg.value);

        })

        // 初始化 WebSocket 连接
        connectWebSocket();

    } catch (error) {
        console.error("请求失败", error);
        ElMessage.error("数据加载失败");
    }

    console.log("聊天测试", username.value, toUsername.value);
});


onUnmounted(() => {
    if (socket.value) {
        socket.value.close();
    }
});
</script>

<style scoped>
.top_bar {
    width: 100%;
    height: 10vh;
    /* background-color: wheat; */
    display: flex;
}

.top_bar img {
    width: 20vh;
    height: auto;
    margin-left: 20vh;
}

.farm_card {
    width: 90vh;
    margin-left: 2vh;
    margin-top: 1vh;
    display: flex;
}

.card_left {
    width: 25vh;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.card_left span {
    margin-top: 2vh;
}

.card_left .card_tags {
    margin: 0;
}

.card_right {
    display: flex;
    gap: 2vh;
    margin-top: 2vh;
}

.card_right span {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: rgb(255, 56, 56);
}

.top_bar .search {
    width: 50vh;
    margin: auto;
    margin-left: -16vh;
    display: flex;
}

.search .search_btn_v {
    background-color: green;
    font-size: 1.8vh;
    font-weight: bold;
}


.body {
    display: flex;
    flex-wrap: wrap;
    background-color: #E8E8E8;
}

.select_bar {
    background-color: green;
    color: white;
    width: 80%;
    margin: auto;
}

.one_box {
    background-color: white;
    width: 80%;
    height: 60vh;
    margin: auto;
    display: flex;
}

.one_left {
    width: 80%;
    height: 90%;
    background-color: white;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.img_box {
    width: 50%;
    height: 62%;
    margin: auto;
    margin-top: 4vh;
    border-radius: 1vh;
}

.one_right {
    width: 100%;
}

.right_body {
    margin-top: 4vh;
    margin-left: 10vh;
}

.one_desc {
    color: gray;
    font-size: 2vh;
}

.one_price {
    display: flex;
    margin-top: 2vh;
}

.one_address {
    position: relative;
    margin-top: 2vh;
}

.address-list {
    position: absolute;
    background-color: #fff;
    border: 1px solid #ccc;
    padding: 10px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    z-index: 100;
    width: 300px;
}

.arrow-icon i {
    cursor: pointer;
    font-size: 1em;
    color: #949494;
}

.rotate-up {
    animation: rotateUpAnimation 0.3s linear forwards;
}

.rotate-down {
    animation: rotateDownAnimation 0.3s linear forwards;
}

@keyframes rotateUpAnimation {
    from {
        transform: rotate(180deg);
    }

    to {
        transform: rotate(0deg);
    }
}

@keyframes rotateDownAnimation {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(180deg);
    }
}

.Address_card:hover {
    border: red 1px solid;
    border-radius: 5px;
}

.one_sure {
    margin-top: 2vh;
}

.one_size {
    margin-top: 2vh;
}

.one_buyNum {
    margin-top: 2vh;
    display: flex;
}


.two_box {
    background-color: white;
    width: 80%;
    height: auto;
    margin: auto;
    margin-top: 2vh;
}

.image-container {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
    padding: 0.5vh;
}

.three_box {
    background-color: red;
    width: 80%;
    height: 60vh;
    margin: auto;
    margin-top: 2vh;
}

.chat-window {
    display: flex;
    flex-direction: column;
    height: 400px;
}

.chat-messages {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 10px;
}

.message {
    margin-bottom: 10px;
}

.message-sender,
.message-receiver {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}

.message-sender {
    justify-content: flex-end;
    color: blue;
}

.message-receiver {
    justify-content: flex-start;
    color: green;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
}

.avatar-sender {
    margin-right: 10px;
}

.avatar-receiver {
    margin-left: 10px;
}

.message-content {
    max-width: 70%;
    padding: 10px;
    border-radius: 10px;
    background-color: #f1f1f1;
}

/* From Uiverse.io by btongheng */
.free_button {
    --😀: #644dff;
    --😀😀: #4836bb;
    --😀😀😀: #654dff63;
    cursor: pointer;
    width: 184px;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 1rem;
    font-size: 1.125em;
    font-weight: 800;
    letter-spacing: 2px;
    color: #fff;
    background: var(--😀);
    border: 2px solid var(--😀😀);
    border-radius: .75rem;
    box-shadow: 0 8px 0 var(--😀😀);
    transform: skew(-10deg);
    transition: all .1s ease;
    filter: drop-shadow(0 15px 20px var(--😀😀😀));
}

.free_button:active {
    letter-spacing: 0px;
    transform: skew(-10deg) translateY(8px);
    box-shadow: 0 0 0 var(--😀😀😀);
}
</style>
